<template>
<!--  系统变量页面-->
  <div class="page">
    <!-- 条件筛选 -->
    <div class="page_filter">
      <el-input v-model="form.name" clearable placeholder="变量名称"></el-input>
      <el-input v-model="form.info" clearable placeholder="变量描述"></el-input>
      <el-button class="common_btn-defalut" icon="el-icon-search" @click="form.page=1;queryList()">搜索</el-button>
    </div>
    <div class="page_main">
      <el-button icon="el-icon-plus" @click.stop="handleAdd" class="common_btn-small">新增系统变量</el-button>
      <!-- table -->
      <el-table
        :data="tableList"
        border>
        <el-table-column
          label="序号"
          fixed
          width="80">
          <template slot-scope="scope">
            {{getIndex(scope.$index)}}
          </template>
        </el-table-column>
        <el-table-column
          prop="name"
          label="变量名称"
          width="220">
        </el-table-column>
        <el-table-column
          prop="value"
          label="值"
        width="220">
        </el-table-column>
        <el-table-column
          prop="type"
          label="类型"
          width="80">
        </el-table-column>
        <el-table-column
          prop="info"
          show-overflow-tooltip
          label="描述"
          width="220">
        </el-table-column>
        <el-table-column
          prop="creator"
          label="创建人"
          width="120">
        </el-table-column>
        <el-table-column
          prop="operator"
          label="更新人"
          width="120">
        </el-table-column>
        <el-table-column
          label="创建时间"
          width="180">
          <template slot-scope="scope">{{scope.row.createTime | formatTimer}}</template>
        </el-table-column>
        <el-table-column
          label="更新时间"
          width="180">
          <template slot-scope="scope">{{scope.row.updateTime | formatTimer}}</template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="210">
          <template slot-scope="scope">
            <el-button type="text" class="btn_edit" @click="handleEdit(scope.row)">编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="form.page"
        :page-size="form.pageSize"
           :page-sizes="[10, 20, 30, 40,50,60,70,80,90,100]"
              layout="sizes, prev, pager, next"
        :total="form.total">
      </el-pagination>
    </div>

    <!-- 新增编辑弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="isShowDialog" :close-on-click-modal="false" width="962px">
      <!-- 具体form表单 -->
      <el-form label-position="right" ref="form" :rules="rules" :model="currentRow" label-width="100px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="currentRow.name" placeholder="请输入变量名称"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model.trim="currentRow.type" clearable>
            <el-option v-for="item in typeList" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="info">
          <el-input v-model="currentRow.info"  placeholder="变量描述"></el-input>
        </el-form-item>
        <el-form-item label="值" prop="value">
          <el-input v-model="currentRow.value"  type="textarea" :autosize="{ minRows: 8}"  style="width: 520px" placeholder="请输入值"></el-input>
        </el-form-item>
      </el-form>
      <!-- 操作按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button class="common_btn-white" @click="isShowDialog = false">取消</el-button>
        <el-button class="common_btn-defalut" type="primary" @click="validateForm">确定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
  import { sysConfigList, sysConfigAdd, sysConfigUpdate } from '@/services/model/sys'
  import Format from '@/utils/format'
  // form表单校验规则
  const RULES = {
    name: { required: true, message: '请输入变量名称' },
    type: { required: true, message: '请选择变量类型' },
    info: { required: true, message: '请输入变量描述' },
    value: { required: true, message: '请输入变量值' },
  }
  export default {
    data () {
      return {
        form: {
          page: 1,
          pageSize: 10
        },
        rules: RULES, // 表单校验的规则
        tableList: [],
        isShowDialog: false, // 是否显示弹窗
        currentRow: {}, // 新增数据
        defaultProps: {
          children: 'subMenu',
          label: 'name'
        },
        typeList:["Integer","Double","String","JSON"],
      }
    },
    computed: {
      // 弹窗的title
      dialogTitle () {
        return this.currentRow.id ? '编辑系统变量' : '新增系统变量'
      },
    },
    filters: {
      // 时间格式化
      formatTimer (timer) {
        return Format(new Date(timer), 'yyyy-MM-dd hh:mm:ss')
      }
    },
    methods: {
      // 当前变化的节点
      // 获取当前的序号
      getIndex (index) {
        let param = (this.form.page - 1) * this.form.pageSize + index + 1
        return param
      },
      // 分页大小改变
      handleSizeChange (val) {
        this.form.pageSize = val
        this.queryList()
      },
      /**
       * row  当前操作行的对象
       */
      handleEdit(row) {
        this.isShowDialog = true
        this.currentRow = JSON.parse(JSON.stringify(row))
        this.$nextTick(() => {
          this.$refs.form.clearValidate()
        })
      },

    // 当前页码改变
    handleCurrentChange (val) {
      this.form.page = val
      this.queryList()
    },
      // 处理删除
      async handleDelete (row) {
        let res = await roleDelete({ id: row.id })
        if (res.code === 200) {
          this.$notify({
            type: 'success',
            title: '提示',
            message: '数据已删除'
          })
          this.queryList()
        }
      },
      async queryList () {
        // 由于在前端进行过滤，所以name不能传到后端
        let res = await sysConfigList(this.form)
        this.tableList = res.data?.records || []
        this.form.page = Number(res.data?.current)
        this.form.total = Number(res.data?.total)
      },
      // 新增数据
      handleAdd () {
        this.currentRow = {}
        this.isShowDialog = true
        this.$nextTick(() => {
          this.$refs.form.clearValidate()
        })
      },
      isInteger(value) {         //验证是否为数字
        var patrn = /^(0|[1-9][0-9]*|-[1-9][0-9]*)$/;
        if (patrn.exec(value) == null || value == "") {
          return false
        } else {
          return true
        }
      },
      isDouble(value) {         //验证是否为数字
        var patrn = /^(-)?\d+(\.\d+)?$/;
        if (patrn.exec(value) == null || value == "") {
          return false
        } else {
          return true
        }
      },

      // 表单提交
      validateForm () {
        //校验值是否和所选类型匹配
        if(this.currentRow.type == 'Integer'){
          if(!this.isInteger(this.currentRow.value) ){
            this.$notify({
              type: 'warning',
              title: '提示',
              message: '请输入Integer类型'
            })
            return
          }
        }else if(this.currentRow.type == 'Double'){
          if(!this.isDouble(this.currentRow.value) ){
            this.$notify({
              type: 'warning',
              title: '提示',
              message: '请输入Double类型'
            })
            return
          }
        }else if(this.currentRow.type == 'String'){
          if(this.currentRow.value.constructor !== String){
            this.$notify({
              type: 'warning',
              title: '提示',
              message: '请输入String类型'
            })
            return
          }
        }else if(this.currentRow.type == 'JSON'){
          let str = this.currentRow.value
          try {
            str = str.replace(/ \+/g, '')
            str = str.replace(/[\r\n]/g, '')
            let parseJSON = JSON.parse(str)
            JSON.stringify(parseJSON, null, 2)
          } catch (err) {
            this.$message(
              {
                type: 'warning',
                showClose: true,
                message: '请传入正确的json数据！'
              })
            return;
          }
        }
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.submitData()
          }
        })
      },
      // 新增编辑提交数据
      async submitData () {
        // 根据ID判断使用新增还是编辑
        let action = this.currentRow.id ? sysConfigUpdate : sysConfigAdd
        let res = await action(this.currentRow)
        if (res.code === 200) {
          this.$notify({
            type: 'success',
            title: '提示',
            message: this.currentRow.id ? '修改成功' : '添加成功'
          })
          this.isShowDialog = false
          this.queryList()
          return true
        }
      }

  },
  mounted () {
  },
  activated () {
    this.queryList()
  }
}
</script>

<style lang="less" scoped>
  .el-form-item{
    display: inline-block !important;
  }
  .dialog_relate {
    .dialog_filter {
      display: flex;
      margin-bottom: 22px;
      .el-input {
        margin-right: 10px;
        width: 200px;
      }
    }
  }
  /deep/.tree_scroll .el-scrollbar__wrap {
    max-height: 50vh;
    height: 300px;
  }
  /deep/.role_tree {
    .el-checkbox__input.is-checked .el-checkbox__inner, .el-checkbox__input.is-indeterminate .el-checkbox__inner {
      background-color: #0DC26B;
      border-color: #0DC26B;
    }
    .el-checkbox__inner:hover {
      border-color: #0DC26B;
    }
  }
  .el-dialog__wrapper .el-dialog {
    width: auto;
    border-radius: 9px;
  }
</style>
